class Order extends React.Component {

    constructor(props){
        super(props);

        this.payModuleMap = {
            "CAR":"停车缴费",
            "PROPERTY" :"物业缴费",
        }

        this.payTypeMap = {
            "wx_app":"微信APP支付",
            "wx_h5":"微信支付",
            "alipay":"支付宝支付",
            "cash":"现金支付"
        }

        this.orderState = {
            "0":"未支付",
            "1":"已支付"
        }

        this.state = {
            orders : [],
            orderInfo : {},
            payModuleInfos : []
        }

        this.pageCount = 0;
    }

    dataTransfer(data){
        for(let i=0;i<data.length;i++){
            data[i].payType = this.payTypeMap[data[i].payType];
        }

        return data;
    }

    updateOrderList(page,pageSize){
        let params = {};
        if(this.refs.dateSelect.value){
            params.dateStart = this.refs.dateSelect.rangeStart;
            params.dateEnd = this.refs.dateSelect.rangeEnd;
        }

        params.commCode = this.refs.commSelect.commCode;
        params.page = page;
        params.pageSize = pageSize;
        params.payModuleName = this.refs.payModuleSelect.value;

        postJson("/pay/getOrdersPage.x",params,(data)=>{
            let dataTrans = this.dataTransfer(data.data.list);
            if(dataTrans) {
                this.pageCount = data.data.size;
                this.setState({orders: dataTrans});
            }
        })
    }

    query(){
        this.refs.table.refresh();
    }

    showDetail(orderId){
        postJson("/pay/getOrderDetail.x",{orderId:orderId},(data)=>{
            console.log(data.data);
            if(data.data) {
                this.setState({orderInfo: data.data});
                this.refs.detail.show();
            }
            else
                layui.layer.msg("未找到详情信息");
        })
    }

    renderDetailData(){
        let data = [];
        for(let key in this.state.orderInfo){
            data.push(
                <tr>
                    <td>{key}:</td>
                    <td>{this.state.orderInfo[key]}</td>
                </tr>
            )
        }
        return data;
    }

    sortRecord(a,b){
        if(a.payModule.length !== b.payModule.length) {
            return a.payModule.length - b.payModule.length;
        }
        else {
            if (a.payModule !== b.payModule) {
                for (let i = 0; i < a.payModule.length; i++) {
                    if (a.payModule.charAt(i) !== b.payModule.charAt(i))
                        return a.payModule.charAt(i) - b.payModule.charAt(i);
                }
            } else if (!a.time || !b.time) {
                return true;
            } else {
                for (let i = 0; i < a.time.length; i++) {
                    if (a.time.charAt(i) !== b.time.charAt(i))
                        return a.time.charAt(i) - b.time.charAt(i);
                }
            }
        }
    }

    orders2ExcelArray(data){
        data.sort(this.sortRecord);
        console.log(data);
        let page = [];
        let line1 = ['订单编号','订单类型','支付状态','支付类型','应付金额','实付金额','支付时间','附加数据1','附加数据2'];
        page.push(line1);
        let totalFee = 0;
        let payModuleTotalFee = 0;
        let payModule = data[0].payModule;
        for(let i=0; i < data.length; i++){
            let line = [];
            line.push(data[i].id+" ");
            line.push(this.orderTypeMap[data[i].orderType]);
            line.push(this.orderState[data[i].orderState]);
            line.push(this.payTypeMap[data[i].payType]);
            line.push(data[i].payableFee);
            line.push(data[i].totalFee);
            line.push(data[i].time);
            line.push(data[i].attach);
            line.push(data[i].attach2);
            page.push(line);

            totalFee += parseFloat(data[i].totalFee);
            payModuleTotalFee += parseFloat(data[i].totalFee);
            if((i+1 === data.length && payModuleTotalFee !== totalFee) || (i+1 !== data.length && data[i+1].payModule !== payModule)){
                page.push(['']);
                page.push(['支付模块：',this.orderTypes[data[i].payModule].orderDesc,'总金额',payModuleTotalFee]);
                page.push(['']);
                payModuleTotalFee = 0;
                if(i+1 !== data.length)
                    payModule = data[i+1].payModule;
            }
        }

        let dates = this.refs.dateSelect.value.split("~");
        page.unshift(['']);
        page.unshift([dates[0],dates[1],totalFee]);
        page.unshift(['起始时间','结束时间','所有支付总金额']);
        return page;
    }

    exportExcel(){

        if(!this.refs.dateSelect.value){
            layui.layer.alert("请选择时间!");
            this.refs.dateSelect.value = '';
            return;
        }

        let dates = this.refs.dateSelect.value.split("~");
        let dateStart = Date.parse(dates[0]);
        let dateEnd = Date.parse(dates[1]);
        let range = dateEnd - dateStart;
        if(range / 1000 / 3600 / 24 > 93){
            layui.layer.alert("时间范围不能超过3个月!");
            this.refs.dateSelect.value = '';
            return;
        }

        layui.layer.confirm("确定要导出账单么?",(index)=>{
            let params = {
                commCode:this.refs.commSelect.commCode,
                payModuleName : this.refs.payModuleSelect.value,
                state : 1,
                dateStart : dates[0],
                dateEnd : dates[1]
            }
            this.refs.export.exportExcel("/pay/getOrders.x",params,(data)=>this.orders2ExcelArray(data));
            layui.layer.close(index);
        })
    }

    onChangeComm(comm){
        this.refs.table.refresh();

        postJson("/pay/getValidModulesForComm.x",{commCode : comm},(data)=>{
            let orders = data.data;
            /* 先去重复 */
            this.orderTypes = {};
            for(let i=0;i<orders.length;i++)
                this.orderTypes[orders[i].orderType] = orders[i];

            orders = [];
            for(let key in this.orderTypes)
                orders.push(this.orderTypes[key]);

            this.setState({payModuleInfos : orders});
        })

    }

    render(){
        return (
            <Frame header="订单列表">
                <Form type="pane">
                    <Item>
                        <LayuiCommSelect mask={['building','unit','floor','room']}
                                         ref="commSelect" lay-verify="required" formLabelName="小区"
                                         onChangeComm={(comm)=>this.onChangeComm(comm)}/>

                        <Label>支付类型</Label>
                        <Select ref="payModuleSelect">
                            <option value="">所有</option>
                            {
                                this.state.payModuleInfos.length > 0?this.state.payModuleInfos.map((data)=>{
                                    return (<option value={data.orderType}>{data.orderDesc}</option>)
                                }):''
                            }
                        </Select>
                        <Label>时间选择</Label>
                        <DateSelect range="true" ref="dateSelect"/>
                        <Button onClick={()=>this.query()}>查询</Button>
                    </Item>
                    <Table count={this.pageCount} pageOnClick={(page,pageSize)=>this.updateOrderList(page,pageSize)} size="sm"
                           toolbar={
                               <FileExportButton
                                   ref="export"
                                   exportFileName="对账单"
                                   onClick={() => this.exportExcel()}
                               >导出账单
                               </FileExportButton>
                           }
                           ref="table"
                    >
                        <thead>
                            <tr>
                                <th>订单编号</th>
                                <th>订单类型</th>
                                <th>订单子类型</th>
                                <th>支付类型</th>
                                <th>应付金额</th>
                                <th>实付金额</th>
                                <th>订单状态</th>
                                <th>下单时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                        {
                            this.state.orders.length > 0 ?this.state.orders.map((order)=>{
                                return (
                                    <tr>
                                        <td>{order.id}</td>
                                        <td>{this.payModuleMap[order.payModule]}</td>
                                        <td>{order.body}</td>
                                        <td>{order.payType}</td>
                                        <td>{parseFloat(order.payableFee) + "元"}</td>
                                        <td>{parseFloat(order.totalFee) + "元"}</td>
                                        <td style={{color:order.orderState === 0?'red':'green'}}>{this.orderState[order.orderState]}</td>
                                        <td>{order.time}</td>
                                        <td>
                                            <Button size="xs" onClick={()=>this.showDetail(order.id)}>查看详情</Button>
                                        </td>
                                    </tr>
                                )
                            }):''
                        }
                        </tbody>
                    </Table>
                </Form>
                <Modal ref="detail">
                    <Table size="sm">
                        <tbody>
                        {
                            this.renderDetailData()
                        }
                        </tbody>
                    </Table>
                </Modal>
            </Frame>
        )
    }
}

ReactDOM.render(<Order/>,document.getElementById("order"));